package com.itheima.web.filters;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.constant.MessageConstant;
import com.itheima.domain.Result;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebFilter(urlPatterns = {"/system/*","/store/*"})
public class PermissionFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
//        获取访问路径
        String servletPath = request.getServletPath();
//        得到/system/dept 或者 /system/user
        String pathInfo = request.getPathInfo();
//        得到标记/findByPage/findAll/save/edit
        if (pathInfo.substring(1).startsWith("find")||pathInfo.substring(1).startsWith("select")){
            chain.doFilter(req,resp);
            return;
        }
        List<String> curls = (List<String>) request.getSession().getAttribute("curls");
        if (curls!=null&&curls.contains(servletPath+pathInfo)){
            chain.doFilter(req,resp);
        }else {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.writeValue(response.getOutputStream(),new Result(false, MessageConstant.PERMISSION_FORBIDDEN));
        }
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
